/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-11-20 22:17:24
 * 天凉好个秋
 */

import { Context } from "koa";
import UserService from '../service/UserService'
import response from "../../utils/response";
import requestParams from "../../utils/requestParams";
import { Rules } from "async-validator";
import vaildate from "../../utils/validate";
import { sign, verify } from "../../utils/auth";
import pagination from "../../utils/pagination";
import {encryptPassword} from '../../utils/util'

// 用户控制器
class UserControll {

  // 根据用户名查询用户信息
  async getUserByName(ctx: Context) {
    const {name} = requestParams(ctx)
    if(!name) return response.error(ctx, '请输入用户名')
    const data = await UserService.getUserByName(name);
    if(data !== null) return response.success(ctx, data)
    response.error(ctx, '用户不存在')
    
  }

  // 获取用户列表
  async getUserList(ctx: Context) {
    const { pageIndex, limit } = requestParams(ctx)
    const { count, rows } = await UserService.getUserList(Number(pageIndex), Number(limit))
    response.success(ctx, pagination(rows, pageIndex, count, limit))
  }

  // 添加用户
  async addUser(ctx: Context) {
    const token = ctx.header['authorization']
    if(token === undefined) return response.error(ctx, '未登录')
    const { error: tokenError } = verify(token)
    
    if(tokenError != null)  return response.error(ctx, tokenError)
    const rules: Rules = {
      name: [
        { type: 'string', required: true, message: '用户名不能为空' }
      ],
      password: [
        { type: 'string', required: true, message: '密码不能为空' },
        { min: 6, max: 15, message: '密码长度应在6-15位之间' }
      ]
    }
    interface IUser {
      name: string,
      password: string | number
    }
    const { data, error } = await vaildate<IUser>(ctx, rules)
    if(!error) {
      const hasUser = await UserService.getUserByName(data.name)
      if(hasUser !== null) return response.error(ctx, '该用户名已被注册')
      data.password = encryptPassword(data.password as string)
      const res = await UserService.addUser(data);
      res["dataValues"].token = sign(res);
      response.success(ctx, res)
    } else {
      response.error(ctx, error)
    }
  }


  // 更新用户信息
  async updateUser(ctx: Context) {
    const token = ctx.header['authorization']
    if(token === undefined) return response.error(ctx, '未登录')
    const { error: tokenError } = verify(token)
    
    if(tokenError != null)  return response.error(ctx, tokenError)
    const id = ctx.params['id'] as number
    const hasUser = await UserService.getUserById(id)
    if(!hasUser) return response.error(ctx, '用户不存在')
    
    
    const rules: Rules = {
      name: [
        { type: 'string', required: true, message: '用户名不能为空' }
      ],
      password: [
        { type: 'string', required: true, message: '密码不能为空' },
        { min: 6, max: 15, message: '密码长度应在6-15位之间' }
      ]
    }
    interface IUser {
      name: string,
      password: string | number
    }
    const { data, error } = await vaildate<IUser>(ctx, rules)
    if(!error) {
      const hasUser = await UserService.getUserByName(data.name)
      if(hasUser !== null) return response.error(ctx, '该用户名已存在')
      data.password = encryptPassword(data.password as string)
      const [number] = await UserService.updateUser(id, data)
      if (number > 0) {
        response.success(ctx)
      } else {
        response.error(ctx, '更新失败')
      }
    } else {
      response.error(ctx, error)
    }
  }

  // 删除用户
  async deleteUser(ctx: Context) {
    const token = ctx.header['authorization']
    if(token === undefined) return response.error(ctx, '未登录')
    const { error: tokenError } = verify(token)
    
    if(tokenError != null)  return response.error(ctx, tokenError)
    const id = ctx.params['id'] as number
    const hasUser = await UserService.getUserById(id)
    if(!hasUser) return response.error(ctx, '用户不存在')
    
    const number = await UserService.deleteUser(id)
    if(number > 0) {
      return response.success(ctx)
    } else {
      response.error(ctx, '删除失败')
    }
  }
}

export default new UserControll;
